<?php

namespace App\Middleware;

use App\Models\MasterAccess;
use App\Models\MasterMenu;
use App\Models\MasterPermission;
use Closure;
use common\enum\CommonEnum;
use common\utils\RedisKeys;
use common\utils\SysCode;
use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class Authenticate
{
    /**
     * The authentication guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if ($this->auth->guard($guard)->guest()) {
            return response('Unauthorized.', 401);
        }
        $authCheck = $this->authCheck($request);
        if ($authCheck !== true){
            error_exit(SysCode::ROLE_AUTH_NO_MATCH);
        }
        $kickCheck = $this->kickCheck($request);
        if ($kickCheck !== true){
            error_exit($kickCheck);
        }
        return $next($request);
    }

    //权限验证
    private function authCheck($request)
    {
        $uris = parse_url($request->url());
        $path = $uris['path'];
        $method = $request->method();
        $method = strtolower($method);
        $user = $request->user();
        if (!$user){
            return true;
        }
        $userRole = $user->role;
        if ($userRole == CommonEnum::ADMIN_ROLE_ID){
            return true;
        }
        //判断操作是否存在
        $accessId = MasterAccess::where(['api'=>$path,'method'=>$method])->value('id');
        $where['role_id'] = $userRole;
        if($accessId){
            $where['access_id'] = $accessId;
        }else{
            return true;
        }
        //判断改用户是否有权限
        $exists = MasterPermission::where($where)->exists();
        if (!$exists){
            return false;
        }
        return true;
    }

    //管理员踢线验证
    public function kickCheck($request)
    {
        $user = $request->user();
        $operateId = $user['id'];
        $redis = Redis::connection();
        $key = RedisKeys::KICK_ADMIN.$operateId;
        $value = $redis->get($key);
        if ($value){
            return SysCode::ADMIN_USER_MSG_CHANGED;
        }
        return true;
    }
}
